#include "utils.hpp"
#include <filesystem>
#include <iostream>

namespace fs = std::filesystem;

namespace impl
{
template <typename Dur>
bool is_older_than(fs::path const& path, Dur const dur)
{
    auto last_wr = fs::last_write_time(path);
    auto ftime = last_wr.time_since_epoch();
    auto nowdur = (sysclock::now() - dur).time_since_epoch();
    return durcast(nowdur - ftime, Dur{}).count() > 0;
}

bool prompt()
{
    std::string opt;
    std::cout << "do you wish to continue? [y/N]\n";
    std::cin >> opt;
    if (opt.find_first_of("yY") == opt.npos)
    {
        std::cout << "No\n";
        return false;
    }
    else if (opt == "yes" || opt == "Yes" || opt == "YES")
    {
        std::cout << "Yes\n";
        return true;
    }
    return false;
}

template <typename Dur>
void remove_files_older_than(fs::path const& path, Dur const dur)
{
    try
    {
        if (fs::exists(path))
        {
            if (is_older_than(path, dur))
            {
                std::cout << "Deleting " << path;
                if (prompt())
                {
                    fs::remove(path);
                    std::cout << path << " deleted\n";
                }
                else
                {
                    std::cout << "abort...\n";
                    return;
                }
            }
            else if (fs::is_directory(path))
            {
                for (auto const& ent : fs::directory_iterator(path))
                {
                    remove_files_older_than(ent.path(), dur);
                }
            }
        }
    }
    catch (std::exception& e)
    {
        std::cerr << e.what() << '\n';
    }
}

}  // namespace impl

using namespace std;
int main(int argc, char** argv)
{
    using namespace chrono_literals;
    string path;
    cout << "Input path you wish to delete: ";
    cin >> path;
    impl::remove_files_older_than(path, 1h);
    return 0;
}